package com.teddy.DTXMB.Controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.teddy.DTXMB.Model.Product;
import com.teddy.DTXMB.Service.CategoryService;
import com.teddy.DTXMB.Service.ProductService;
import com.teddy.DTXMB.Service.ShoppingCartService;
import com.teddy.DTXMB.Model.Category;
import com.teddy.DTXMB.Model.Custom;


/**
 * Home 主页
 */
@Controller
@SessionAttributes("custom")
public class HomeController {
	/*Log实例*/
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/*Service实例，因为有了@Autowired可以不用显式实例化*/
	@Autowired
	private ProductService productService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private CategoryService categoryService;
	
	/*默认根目录，进入首页*/
	/*这里的@ModelAttribute和@SessionAttributes对应使用，可以读取session中的custom信息*/
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(@ModelAttribute("custom") Custom custom, Model model) {
		logger.info("Welcome To DTXMB....");
		try{
			/*所有产品*/
			List<Product> products = productService.getAllProduct();
	        model.addAttribute("products", products);
	        /*所有目录*/
	        List<Category> categories = categoryService.getAllRootCategory();
	        model.addAttribute("categories", categories);
	        
			/*若是已登陆状态，则展示购物车信息*/
	        if(custom != null){
				int cartNumber = shoppingCartService.getShoppingCartByCustomID(custom.getId()).size();
				model.addAttribute("cartnumber", cartNumber);
				}
			return "home";
		}
		catch (Exception e){
			/*发生异常，返回到“错误用户”页面*/
			e.printStackTrace();
			return "errorcustom";
		}
	}
	
	/*@ModelAttribute的初始化，若第一次进入页面，则可以初始化一个custom*/
	@ModelAttribute("custom")
	public Custom initCustom(){
		return new Custom();
	}
}